#!/bin/sh
#
# $FreeBSD$
#

# PROVIDE: ix-ups
# REQUIRE: FILESYSTEMS
# BEFORE: nut

. /etc/rc.subr

UPS_CONFPATH="/usr/local/etc/nut"
UPS_CONFIG="${UPS_CONFPATH}/ups.conf"
UPS_MONFILE="${UPS_CONFPATH}/upsmon.conf"
UPS_SCHEDFILE="${UPS_CONFPATH}/upssched.conf"
UPS_USERSFILE="${UPS_CONFPATH}/upsd.users"
UPS_DAEMONFILE="${UPS_CONFPATH}/upsd.conf"
UPS_VARPATH="/var/db/nut"

generate_ups()
{
    local IFS="|"
    local f="id ups_identifier ups_driver ups_port ups_description"
    eval local $f
    local sf=$(var_to_sf $f)
    ${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} \
	"SELECT $sf FROM services_ups ORDER BY -id LIMIT 1" | \
	while eval read $f; do
            if [ "$(echo "${ups_driver}"|cut -d"$" -f 1)" = "mge-shut or oldmge-shut" ]; then
                driver="mge-shut"
            else
                driver=$(echo "${ups_driver}"|cut -d"$" -f 1|tr -s " " "\n")
            fi
	    cat <<EOF
[${ups_identifier}]
    driver = ${driver}
    port = ${ups_port}
    desc = "${ups_description}"
EOF
    ${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} \
    "SELECT ups_options FROM services_ups WHERE id = ${id}"
    done
}

generate_upsmon()
{
    local IFS="|"
    local f="ups_mode ups_remotehost ups_remoteport ups_monuser ups_monpwd ups_identifier ups_shutdown ups_shutdowntimer ups_shutdowncmd ups_nocommwarntime ups_emailnotify ups_toemail ups_subject ups_powerdown"
    eval local $f
    local sf=$(var_to_sf $f)
    local user passwd ident powerdown
    ${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} \
	"SELECT $sf FROM services_ups ORDER BY -id LIMIT 1" | \
	while eval read $f; do

		user=`echo ${ups_monuser}|sed -E 's/([#$])/\\\1/g'`
		passwd=`/usr/local/bin/midclt call notifier.pwenc_decrypt ${ups_monpwd}|sed -E 's/([#$])/\\\1/g'`
		if [ "${ups_mode}" = "master" ]; then
			ident="${ups_identifier}"
		else
			ident="${ups_identifier}@${ups_remotehost}:${ups_remoteport}"
		fi
		if [ "${ups_powerdown}" = "1" ]; then
			powerdown="/etc/killpower"
		else
			powerdown="/etc/nokillpower"
		fi

		cat <<EOF
FINALDELAY ${ups_shutdowntimer}
MONITOR ${ident} 1 ${user} ${passwd} ${ups_mode}
NOTIFYCMD "/usr/local/sbin/upssched"
NOTIFYFLAG ONBATT SYSLOG+WALL+EXEC
NOTIFYFLAG LOWBATT SYSLOG+WALL+EXEC
NOTIFYFLAG ONLINE SYSLOG+WALL+EXEC
NOTIFYFLAG COMMBAD SYSLOG+WALL+EXEC
NOTIFYFLAG COMMOK SYSLOG+WALL+EXEC
NOTIFYFLAG REPLBATT SYSLOG+WALL+EXEC
NOTIFYFLAG NOCOMM SYSLOG+EXEC
NOTIFYFLAG FSD SYSLOG+EXEC
NOTIFYFLAG SHUTDOWN SYSLOG+EXEC
SHUTDOWNCMD "${ups_shutdowncmd}"
POWERDOWNFLAG ${powerdown}
EOF

		if [ -n "${ups_nocommwarntime}" ]; then
			echo "NOCOMMWARNTIME ${ups_nocommwarntime}"
		fi

    done
}

generate_upsdusers()
{

	local user=`${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} "SELECT ups_monuser FROM services_ups ORDER BY -id LIMIT 1"|sed -E 's/(["$#=])/\\\1/g'`
	local passwd=`/usr/local/bin/midclt call notifier.pwenc_decrypt "$(${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} "SELECT ups_monpwd FROM services_ups ORDER BY -id LIMIT 1")"|sed -E 's/(["$#=])/\\\1/g'`
	cat <<EOF
[${user}]
    password = ${passwd}
    upsmon master

EOF

	${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} \
	"SELECT ups_extrausers FROM services_ups ORDER BY -id LIMIT 1"

}

generate_upsd()
{

    local IFS="|"
    local f="id ups_rmonitor"
    eval local $f
    local sf
    sf=$(echo $f | sed -e 's/ /, /g')
    ${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} \
	"SELECT $sf FROM services_ups ORDER BY -id LIMIT 1" | \
	while eval read $f; do
        if [ "${ups_rmonitor}" -eq 1 ]; then
	        echo "LISTEN 0.0.0.0"
        else
	        echo "LISTEN 127.0.0.1"
        fi
    ${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} \
    "SELECT ups_optionsupsd FROM services_ups WHERE id = ${id}"
    done

}

generate_upssched()
{

    local IFS="|"
    local f="ups_shutdowntimer"
    eval local $f
    local sf
    sf=$(var_to_sf $f)
    ${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} \
	"SELECT $sf FROM services_ups ORDER BY -id LIMIT 1" | \
	while eval read $f; do

        cat << __EOF__
CMDSCRIPT   /usr/local/bin/custom-upssched-cmd
PIPEFN      /var/db/nut/upssched.pipe
LOCKFN      /var/db/nut/upssched.lock

AT NOCOMM   * EXECUTE EMAIL
AT COMMBAD  * START-TIMER COMMBAD 10
AT COMMOK   * CANCEL-TIMER COMMBAD COMMOK
AT FSD      * EXECUTE EMAIL
AT LOWBATT  * EXECUTE EMAIL
AT ONBATT   * START-TIMER ONBATT ${ups_shutdowntimer}
AT ONBATT   * EXECUTE EMAIL
AT ONLINE   * CANCEL-TIMER ONBATT ONLINE
AT ONLINE   * EXECUTE EMAIL
AT REPLBATT * EXECUTE EMAIL
AT SHUTDOWN * EXECUTE EMAIL
__EOF__

    done

}

generate_ups_conf()
{
	RO_FREENAS_CONFIG=$(ro_sqlite ${name} 2> /tmp/${name}.fail && rm /tmp/${name}.fail)
	trap 'rm -f ${RO_FREENAS_CONFIG}' EXIT

	local mode
	rm -rf ${UPS_CONFPATH}
	mkdir -p ${UPS_CONFPATH}
	mkdir -p ${UPS_VARPATH}
	chown root:uucp ${UPS_VARPATH}
	chmod g=rwx,o= ${UPS_VARPATH}
	mode=`${FREENAS_SQLITE_CMD} ${RO_FREENAS_CONFIG} "SELECT ups_mode FROM services_ups ORDER BY -id LIMIT 1"`
	if [ "${mode}" = "master" ]; then
		generate_ups > ${UPS_CONFIG}
		generate_upsdusers > ${UPS_USERSFILE}
		generate_upsd > ${UPS_DAEMONFILE}
		chown root:uucp ${UPS_CONFIG} ${UPS_USERSFILE} ${UPS_DAEMONFILE}
		chmod 440 ${UPS_CONFIG} ${UPS_USERSFILE} ${UPS_DAEMONFILE}
	fi
	generate_upsmon > ${UPS_MONFILE}
	generate_upssched > ${UPS_SCHEDFILE}
	chown root:uucp ${UPS_MONFILE} ${UPS_SCHEDFILE}
	chmod 440 ${UPS_MONFILE} ${UPS_SCHEDFILE}
}

name="ix-ups"
start_cmd='generate_ups_conf'
stop_cmd=':'

load_rc_config $name
run_rc_command "$1"
